var orderDetail = JSON.parse(sessionStorage.getItem("serviceProviderorderDetail"));
console.log(orderDetail)
var returnedGoodsall=''
//开票状态判断
setTimeout(function (){
    $('#invoicetype').text(orderDetail.invoiceType);
}, 500);
if(orderDetail.addressReceiverPOList!=null){
    $('#received_name').val(orderDetail.addressReceiverPOList[0].receiverName);
    $('#received_telephone').val(orderDetail.addressReceiverPOList[0].mobile);
}
$("#freight").val("0");
var promotionvaluel=""//立减分摊金额
var usedpoints=""//积分分摊金额
/*定义各种金额*/
var Return_goods = 0;//退货商品金额
var Share_freight=0; //退货商品分摊运费
var Share_coupon=0;//分摊优惠(进位)
var is_returnable_freight=true
if(is_returnable_freight==true){
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
}else {
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
    $(".tui").attr("onclick", "return false;");
    $(".tui").css({"color": "grey"});
}

var yunfie=0
var table; //table对象
var rejectSomeArray = {}; //拒收列表对象
//查询商品信息
productInformation()
function productInformation(){
    $("#datatablejk").hide()
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url: root.serviceProviderManagement.getReverseDetail,
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        async: false,//优先运行
        data: JSON.stringify({
            orderId:orderDetail.orderId

        }),
        success: function (data) {
            returnedGoodsall=data.data.itemResponseList
            var productInformation=""
            if(data.data.itemResponseList !="" && data.data.itemResponseList!=null){
                var arr=data.data.itemResponseList

                //算出该活动的所有商品小计和优惠值
                let ii =""
                let ruleStret = '<tr><td colspan="11"><div>' +
                    '<span style="float: left;">'+ii+'</span>' +
                    '</div></td></tr>';
                productInformation +=ruleStret;

                $.each(arr,function(k,v){
                        if(v.couldRejectCount==0){
                            productInformation+='<tr class="biaoge1" bgcolor="#a9a9a9">' +
                                '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>' + v.skuCode + '</div><div>' + v.productName + '</div><div>' + v.skuInfo + '</div></div></div>' +
                                '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-3"><span id="create_time">' + v.distributeCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-1"><span id="handle_man">'+v.couldRejectCount+'' + v.unitName + '</span></td>' +
                                '<td class="biaoge1-3"><span><input type="text" class="input-text mr-5" disabled="disabled" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">0</span><span style="display: none">0</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">0</span><span style="display: none">0</span><span style="display: none">0</span></span>'+ v.unitName+'</td>'+
                                '</tr>';
                        }else {
                            productInformation+='<tr class="biaoge1">' +
                                '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>' + v.skuCode + '</div><div>' + v.productName + '</div><div>' + v.skuInfo + '</div></div></div>' +
                                '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-3"><span id="create_time">' + v.distributeCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-1"><span id="handle_man">'+v.couldRejectCount+'' + v.unitName + '</span></td>' +
                                '<td class="biaoge1-3"><span><input type="text" class="input-text mr-5" oninput="creatArray('+v.skuCode+',this,\'some\','+0+')" value="" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span></span>'+ v.unitName+'</td>'+
                                '</tr>';
                        }

                    }
                )


            }
            $("#datatable").find("tbody").empty().append($(productInformation));

        },
    })
}
//全部拒收
function rejectAll() {
    $(".jiansuo").val("")
    /*表格渲染*/
    orderList()

    function orderList() {

        $("#datatable").hide()
        $("#datatablejk").show()
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            url: root.serviceProviderManagement.getReverseDetail,
            cache: false, //禁用缓存
            type: "POST",
            dataType: "json",
            async: false,//优先运行
            data: JSON.stringify({
                orderId:orderDetail.orderId

            }),
            success: function (data) {
                var returnedGoods=""
                if(data.data.itemResponseList !="" && data.data.itemResponseList!=null){
                    var arr=data.data.itemResponseList

                    //算出该活动的所有商品小计和优惠值
                    let ii =""
                    let ruleStret = '<tr><td colspan="11"><div>' +
                        '<span style="float: left;">'+ii+'</span>' +
                        '</div></td></tr>';
                    returnedGoods +=ruleStret;

                    $.each(arr,function(k,v){
                            if(v.couldRejectCount==0){
                                returnedGoods+='<tr class="biaoge1" bgcolor="#a9a9a9">' +
                                    '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>' + v.skuCode + '</div><div>' + v.productName + '</div><div>' + v.skuInfo + '</div></div></div>' +
                                    '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-3"><span id="create_time">' + v.distributeCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-1"><span id="handle_man">'+v.couldRejectCount+'' + v.unitName + '</span></td>' +
                                    '<td class="biaoge1-3"><span><input type="text" class="input-text mr-5" disabled="disabled" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">0</span><span style="display: none">0</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">0</span><span style="display: none">0</span><span style="display: none">0</span></span>'+ v.unitName+'</td>'+
                                    '</tr>';
                            }else {
                                returnedGoods+='<tr class="biaoge1">' +
                                    '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>' + v.skuCode + '</div><div>' + v.productName + '</div><div>' + v.skuInfo + '</div></div></div>' +
                                    '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-3"><span id="create_time">' + v.distributeCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-1"><span id="handle_man">'+v.couldRejectCount+'' + v.unitName + '</span></td>' +
                                    '<td class="biaoge1-3"><span><input type="text" class="input-text mr-5" oninput="creatArray('+v.skuCode+',this,\'all\','+0+')" value="'+v.couldRejectCount+'"style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span></span>'+ v.unitName+'</td>'+
                                    '</tr>';
                            }


                        }
                    )


                }
                $("#datatablejk").find("tbody").empty().append($(returnedGoods));

            },
        })
    }

    $("#return_freight").html("0")
    isSetReturnFreight = 0;
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
    $(".tui").css({"color": "#1e79e9"});
    $(".tui").attr("onclick", "setReturnFreight(1)");
    yunfie=0
    //全部拒收
    for(var i = 0; i < returnedGoodsall.length; i++) {
        if(returnedGoodsall[i].couldRejectCount!=0){
            rejectSomeArray[returnedGoodsall[i].skuCode] = {
                productCode: returnedGoodsall[i].skuCode,
                sale_price: returnedGoodsall[i].salePrice,//当前单价
                refundCount: returnedGoodsall[i].couldRejectCount,
                fare:0,//当前运费
                coupon_value:0,//当前优惠价格
                library:returnedGoodsall[i].buyerCount,//当前出库数量
                promotionvalue:0,//当前特价
                activitytype:0,//特价商品
                used_points:0//积分分摊
            }
        }

    }
    var service_fee=$('#service_fee').val()
    var freight=$('#freight').val()
    $('#refund_amount_final').html('0')
    //禁止多次点击全部拒收
    var Return_goodsCS=$("#Return_goods").text();
    if(Return_goodsCS==Return_goods.toFixed(2)){
        layer.msg('已是全部拒收状态', {icon: 5,time:1000});
    }
    Share_freight=0
    Share_coupon=0
    Return_goods=0
    var reduceAmount = 0;
    var usedpoint=0;//积分分摊
    for(var key in rejectSomeArray){
        if(rejectSomeArray[key].refundCount!=0){
            console.log(rejectSomeArray[key].used_points+"积分分摊积分分摊积分分摊积分分摊积分分摊")
        }
        Share_freight+=Number(rejectSomeArray[key].fare)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library);
        Share_coupon+=Number(rejectSomeArray[key].coupon_value)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
        var returnPromotionValue = Number(rejectSomeArray[key].promotionvalue) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
        var used_pointsValue = Number(rejectSomeArray[key].used_points) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
        usedpoint+=used_pointsValue
        // 特价
        console.log(rejectSomeArray[key].activitytype)
        if(10 == rejectSomeArray[key].activitytype){
            Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount) - Number(returnPromotionValue)
        }else{
            console.log("wwwwwwwwwwwwwwwwwwwwww")
            Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount)
            console.log(Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount))
            reduceAmount += returnPromotionValue;
        }
    }

    console.log(Return_goods)
    promotionvaluel=(reduceAmount).toFixed(2)
    usedpoints=(usedpoint).toFixed(2)//积分分摊
    $("#recoupon").html((reduceAmount).toFixed(2))
    $("#integrals").html((usedpoint).toFixed(2))
    if(Return_goods==0){
        $("#Return_goods").html(Return_goods)
    }else{
        $("#Return_goods").html((Return_goods).toFixed(2))
    }

    // 判断是否运费券
    /*if (null != orderDetail.orderCoupon && 20 == orderDetail.orderCoupon.coupon_type) {
        $("#Share_freight").html((Number(Share_freight) - Number(Share_coupon)).toFixed(2))
        $("#Share_coupon").html(0)
    } else {

    }*/
    $("#Share_freight").html((Share_freight).toFixed(2))
    $("#Share_coupon").html((Share_coupon).toFixed(2))
    if ( $("#freight").val() == "0") {
        service(1);
        service(2);
    }
}
var arr = [];
var result = 0;
// 退货数量
function creatArray(skuCode,val,someOrAll,number_decimal) {
    $("#return_freight").html("0")
    isSetReturnFreight = 0;
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
    yunfie=0
    var lijian=0//立减分摊
    var promvalue=0
    var librarys=0//购买数量
    var tui=0//退货数量
    var promvalue2=0
    var lijian2=0//立减分摊2
    var tui2=0//退货数量2
    var liajianarr=0//立減分攤
    var reduceAmount=0
    /*重置各种金额*/
    var Return_goods = 0;//退货商品金额
    var usedpoint=0;//积分分摊
    var Share_freight=0; //退货商品分摊运费
    var Share_coupon=0;//分摊优惠(进位)
    var numbers = $(val).parent().parent().prev().children().text()
    //只能输入一个小数点
    val.value = val.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    val.value = val.value.replace(/^\./g,""); //验证第一个字符是数字
    val.value = val.value.replace(/\.{2,}/g,""); //只保留第一个, 清除多余的
    val.value = val.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    var number = numbers.replace(/[^0-9.]/g,"")
    // 验证输入的退货数量
    checkInput(number, val,number_decimal)
    if(val.value != "" || someOrAll == "some"){
        //当前数量为空的时候值为0
        var refundCountdq=val.value
        if(val.value==''){
            var refundCountdq=0
        }
        rejectSomeArray[val.nextElementSibling.innerHTML] = {
            productCode: val.nextElementSibling.innerHTML,//当前skuid
            sale_price: val.nextElementSibling.nextElementSibling.innerHTML,//当前单价
            refundCount:refundCountdq,//当前输入退货数量
            fare:val.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前运费
            coupon_value:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前优惠价格
            library:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前出库数量
            activitytypee:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//商品状态是否是特价
            promotionvalue:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//特价商品金额
            activitytype:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//状态
            used_points:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//积分分摊金额
        }
        console.log(val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling)
        var service_fee=$('#service_fee').val()
        var freight=$('#freight').val()
        $('#refund_amount_final').html('0')
        //特价
        var used_pointss=""
        for(var key in rejectSomeArray){
            if(rejectSomeArray[key].used_points==undefined){
                used_pointss=0
            }else {
                used_pointss=rejectSomeArray[key].used_points
            }
            console.log(rejectSomeArray)
            // Return_goods += Number(rejectSomeArray[key].refundCount)*Number(rejectSomeArray[key].sale_price);
            Share_freight+=Number(rejectSomeArray[key].fare)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library);
            Share_coupon+=Number(rejectSomeArray[key].coupon_value)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            var returnPromotionValue = Number(rejectSomeArray[key].promotionvalue) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)

            var used_pointsValue = Number(used_pointss) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            usedpoint+=used_pointsValue

            // 特价
            if(10 == rejectSomeArray[key].activitytype){
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount) - Number(returnPromotionValue)
            }else{
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount)
                reduceAmount += returnPromotionValue;
            }
        }



        var activitytype=val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
        console.log(activitytype)
        console.log(val.value)


        if(activitytype==30||activitytype==20||activitytype==31){

            promvalue= Number(rejectSomeArray[skuCode].promotionvalue);
            librarys= Number( rejectSomeArray[skuCode].library);
            tui=Number( rejectSomeArray[skuCode].refundCount);
            console.log(Number(rejectSomeArray[skuCode].refundCount))
            let tuikuan = promvalue/librarys*tui;
            // console.log(promvalue)
            // console.log(librarys)
            console.log(tui)
            // console.log(tuikuan)
            if (tui>librarys||tui<=0){//小数位购买修改
                console.log(skuCode)
                var newArr = [];
                var newRejectSomeArray = {};
                console.log("asjdaksjdas"+rejectSomeArray.length)
                for(var key in rejectSomeArray){
                    if (skuCode != rejectSomeArray[key].productCode){
                        newRejectSomeArray[rejectSomeArray[key].productCode]={"productCode":rejectSomeArray[key].productCode,"activitytype":rejectSomeArray[key].activitytype,
                            "activitytypee":rejectSomeArray[key].activitytypee,"coupon_value":rejectSomeArray[key].coupon_value,
                            "fare":rejectSomeArray[key].fare,"library":rejectSomeArray[key].library,
                            "promotionvalue":rejectSomeArray[key].promotionvalue,"refundCount":rejectSomeArray[key].refundCount,
                            "sale_price":rejectSomeArray[key].sale_price
                        }

                    }
                }


                for(let i=0;i<arr.length;i++){
                    if (skuCode != arr[i].skuCode){
                        newArr.push({"skuCode":arr[i].skuCode,"tuikuan":arr[i].tuikuan})
                    }
                }
                arr = newArr;
                rejectSomeArray = newRejectSomeArray;
            }else {
                arr.push({"skuCode":skuCode,"tuikuan":tuikuan})
            }
            for(let i=0;i<arr.length;i++){
                console.log(arr[i].tuikuan+"000000000000000000000")
                lijian= lijian +arr[i].tuikuan;
            }

            result = lijian;

        }else {
            lijian = result;
        }

        console.log(lijian+"PPPPPPP66666666666666")

        console.log(rejectSomeArray)
        promotionvaluel=reduceAmount
        usedpoints=(usedpoint).toFixed(2)
        $("#recoupon").html((reduceAmount).toFixed(2))
        $("#integrals").html((usedpoint).toFixed(2))
        if(Return_goods==0){
            $("#Return_goods").html(Return_goods)
        }else{
            $("#Return_goods").html((Return_goods).toFixed(2))
        }


        // 判断是否运费券
        /* if (null != orderDetail.orderCoupon && 20 == orderDetail.orderCoupon.coupon_type) {
             $("#Share_freight").html((Number(Share_freight) - Number(Share_coupon)).toFixed(2))
             $("#Share_coupon").html(0)
         } else {

         }*/
        $("#Share_freight").html((Share_freight).toFixed(2))
        $("#Share_coupon").html((Share_coupon).toFixed(2))
        if ( $("#freight").val() == "0") {
            service(1);
            service(2);
        }
    }else if(val.value != "" || someOrAll == "all"){//全部拒收
        console.log("22222222222222222222eeeeeeeeeeeeeeeeeeeee")
        var promvalue3=""
        var lijian3=""//立减分摊2
        var tui3=""//退货数量2
        var librarys3=""
        //当前数量为空的时候值为0
        var refundCountdq=val.value
        if(val.value==''){
            var refundCountdq=0
        }
        console.log(refundCountdq)
        rejectSomeArray[val.nextElementSibling.innerHTML] = {
            productCode: val.nextElementSibling.innerHTML,//当前skuid
            sale_price: val.nextElementSibling.nextElementSibling.innerHTML,//当前单价
            refundCount:refundCountdq,//当前输入退货数量
            fare:val.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前运费
            coupon_value:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前优惠价格
            library:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前出库数量
            activitytypee:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//商品状态是否是特价
            promotionvalue:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//特价商品金额
            activitytype:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//状态
            used_points:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//积分分摊金额
        }
        var service_fee=$('#service_fee').val()
        var freight=$('#freight').val()
        /*$('#refund_amount_final').html('0')*/
        var used_pointss=""
        for(var key in rejectSomeArray){
            if(rejectSomeArray[key].used_points==undefined){
                used_pointss=0
            }else {
                used_pointss=rejectSomeArray[key].used_points
            }
            // Return_goods += Number(rejectSomeArray[key].refundCount)*Number(rejectSomeArray[key].sale_price);
            Share_freight+=Number(rejectSomeArray[key].fare)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library);
            Share_coupon+=Number(rejectSomeArray[key].coupon_value)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            var returnPromotionValue = Number(rejectSomeArray[key].promotionvalue) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            var used_pointsValue = Number(used_pointss) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            usedpoint+=used_pointsValue
            // 特价
            if(10 == rejectSomeArray[key].activitytype){
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount) - Number(returnPromotionValue)
            }else{
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount)
                reduceAmount += returnPromotionValue;
            }
            console.log(rejectSomeArray[key].refundCount)
        }
        console.log(rejectSomeArray)
        var activitytype=val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
        console.log(activitytype)
        console.log(val.value)


        if(activitytype==30||activitytype==20||activitytype==31){

            promvalue= Number(rejectSomeArray[skuCode].promotionvalue);
            librarys= Number( rejectSomeArray[skuCode].library);
            tui=Number( rejectSomeArray[skuCode].refundCount);
            console.log(Number(rejectSomeArray[skuCode].refundCount))

            let tuikuan = promvalue/librarys*tui;
            console.log(tuikuan)

            if (tui>librarys||tui<=0){//小数位购买修改
                var newArr = [];
                var newRejectSomeArray = {};
                console.log("asjdaksjdas"+rejectSomeArray.length)
                for(var key in rejectSomeArray){
                    if (skuCode != rejectSomeArray[key].productCode){
                        newRejectSomeArray[rejectSomeArray[key].productCode]={"productCode":rejectSomeArray[key].productCode,"activitytype":rejectSomeArray[key].activitytype,
                            "activitytypee":rejectSomeArray[key].activitytypee,"coupon_value":rejectSomeArray[key].coupon_value,
                            "fare":rejectSomeArray[key].fare,"library":rejectSomeArray[key].library,
                            "promotionvalue":rejectSomeArray[key].promotionvalue,"refundCount":rejectSomeArray[key].refundCount,
                            "sale_price":rejectSomeArray[key].sale_price
                        }

                    }
                }


                for(let i=0;i<arr.length;i++){
                    if (skuCode != arr[i].skuCode){
                        newArr.push({"skuCode":arr[i].skuCode,"tuikuan":arr[i].tuikuan})
                    }
                }
                arr = newArr;
                rejectSomeArray = newRejectSomeArray;
            }else {
                arr.push({"skuCode":skuCode,"tuikuan":tuikuan})
            }
            for(let i=0;i<arr.length;i++){
                console.log(arr[i].tuikuan+"000000000000000000000")
                lijian= lijian +arr[i].tuikuan;
            }

            result = lijian;

        }else {
            lijian = result;
        }

        console.log(lijian+"PPPPPPP66666666666666")


        promotionvaluel=reduceAmount
        usedpoints=(usedpoint).toFixed(2)
        $("#recoupon").html((reduceAmount).toFixed(2))
        $("#integrals").html((usedpoint).toFixed(2))
        if(Return_goods==0){
            $("#Return_goods").html(Return_goods)
        }else{
            $("#Return_goods").html((Return_goods).toFixed(2))
        }
        $("#Share_freight").html((Share_freight).toFixed(2))
        $("#Share_coupon").html((Share_coupon).toFixed(2))
    }

    // 退运费金额
    if(isSetReturnFreight){
        $("#return_freight").html($("#Share_freight").html())
    }
    console.log(rejectSomeArray)

}
//服务费
function service(val) {
    var freight=$('#freight').val()
    var Return_goods= $("#Return_goods").text()
    var Share_freight= $("#Share_freight").text()
    var Share_coupon=$("#Share_coupon").text() //分摊优惠
    var recoupon= $("#recoupon").text(); // 立减分摊
    var integrals= $("#integrals").text(); // 积分分摊金额
    var return_freight=$("#return_freight").text() // 退运费（订单运费）
    var total =(Number(Return_goods)+Number(Share_freight)-Number(Share_coupon)-Number(recoupon)-Number(integrals))*0.15 //服务费
    var totals =(Number(Return_goods)-Number(Share_coupon))//运费
    console.log(total)
    if(val==1){

            var refund_amount_final = Number(Return_goods)-Number(freight)-Number(Share_coupon)+Number(return_freight)-promotionvaluel-usedpoints;
            $('#refund_amount_final').html((refund_amount_final).toFixed(2))

    }else{

            var refund_amount_final = Number(Return_goods)-Number(freight)-Number(Share_coupon)+Number(return_freight)-promotionvaluel-usedpoints;
            $('#refund_amount_final').html((refund_amount_final).toFixed(2))

    }
}

function round2(number,fractionDigits){
    with(Math){
        return round(number*pow(10,fractionDigits))/pow(10,fractionDigits);
    }
}
//限制输入框只能输入两位小数
function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
    if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        obj.value = parseFloat(obj.value);
    }
    if (!obj.value || obj.value == '0' || obj.value == '0.0' || obj.value == '0.00') {
        //   alert('退款金额不能为空');
        return;
    }
    //  正常得话继续调后端接口
}
//输入拒收数量校验
function checkInput(number, e,number_decimal) {

    var value = $(e).val();
    var reg = /[^0-9.]/g;
    // 为空
    if (value == null || value == "") {
        // showErrorMsg(e, "不能为空，请输入");
    }
    // 数字和.
    if (reg.test(value) == true) {
        showErrorMsg(e, "格式错误，请重新输入");
        $(e).val(reg.match(value));
        return false;
    }
    //判断小数购买
    if(value!=""){
        if(value.toString().split(".")[1]!=undefined){
            if(value.toString().split(".")[1].length>number_decimal){
                showErrorMsg(e, "不符合该商品的可退范围");
                return false;
            }
        }

    }
    if(number_decimal==0){
        if(value=="0"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }else if(number_decimal==1){
        if(value=="0.0"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }else if(number_decimal==2){
        if(value=="0.00"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }else if(number_decimal==3){
        if(value=="0.000"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }
    value = Number(value);
    number = Number(number);
    // 大于购买数量
    console.log(number)
    console.log(value)
    if (value > number) {
        showErrorMsg(e, "拒收数量不能大于可拒收数量");
        return false;
        if(value==0){
            $(e).val(number);// 默认数量
        }
        // 为0或者负数
    }

}
function showErrorMsg(e, msg) {
    // 清空非法数据
    $(e).val("");
    $.Huimodalalert(msg, 2000);
}
var isIng = false;
function rejectIntercept() {
    if(isIng){
        layer.msg('请求已提交，请勿重复点击！');
        return false;
    }
    isIng = true;
    /*最终退款总金额*/
    var refund_amount_final = 0;
    var listOrderRefundItems = [];
    for(var key in rejectSomeArray) {
        if(rejectSomeArray[key].refundCount!="") {
            listOrderRefundItems.push(rejectSomeArray[key])
        }
    }
    for(var i=0;i<listOrderRefundItems.length;i++){
        delete listOrderRefundItems[i].activitytype;
        delete listOrderRefundItems[i].activitytypee;
        delete listOrderRefundItems[i].coupon_value;
        delete listOrderRefundItems[i].fare;
        delete listOrderRefundItems[i].library;
        delete listOrderRefundItems[i].promotionvalue;
        delete listOrderRefundItems[i].sale_price;
        delete listOrderRefundItems[i].used_points;
    }
    console.log(listOrderRefundItems)

    if(listOrderRefundItems==""){

        layer.msg("校验：拒收明细不能为空", {icon: 5, time: 1000});
        isIng=false;
        return false
    }
    if(yunfie==0){
        var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >确定不退运费吗？</span>', {closeBtn:false,title:'提示',btn: ['确定', '取消']}, function(index){
            $.ajax({
                contentType: "application/json",
                type: "POST",
                url: root.serviceProviderManagement.refundApply,
                cache: false, //禁用缓存
                dataType: "json",
                data: JSON.stringify({
                    "orderId": orderDetail.orderId,
                    "returnReason":parseInt($("#rejectionReason").val()),
                    "returnDesc": $("#rejectRemark").val(),
                    "receiverName": $("#received_name").val(),
                    "receiverTelephone": $("#received_telephone").val(),
                    "serviceFee": 0,
                    "shippingFee": parseInt($("#freight").val()),
                    "refundSorce": 11,
                    "operatorRole":20,
                    "returnShippingFlag": isSetReturnFreight,
                    "refundAmountFinal": $("#refund_amount_final").html(),
                    "refundRemark": $("#returnMoneyRemark").val(),
                    "operatorId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                    "operatorName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                    "productList": listOrderRefundItems,

                }),
                success: function(result) {
                    if(result.code == "0"){
                        layer.msg('修改成功', {icon: 6,time:1000});
                        setTimeout( function () {
                            var index =  parent.location.reload();
                            parent.layer.close(index)
                        },1000);
                    }else{
                        isIng=false;
                        layer.msg(result.msg, {icon: 5, time: 1000});
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    isIng = false;
                }
            });
            isIng = false;
            layer.close(curInd);
        },function(){
            isIng = false;
            layer.close(curInd);
        });
    }else {
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.serviceProviderManagement.refundApply,
            cache: false, //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                "orderId": orderDetail.orderId,
                "returnReason": $("#rejectionReason").val(),
                "returnDesc": $("#rejectRemark").val(),
                "receiverName": $("#received_name").val(),
                "receiverTelephone": $("#received_telephone").val(),
                "serviceFee": 0,
                "shippingFee": $("#freight").val(),
                "refundSorce": 11,
                "operatorRole":20,
                "returnShippingFlag": isSetReturnFreight,
                "refundAmountFinal": $("#refund_amount_final").html(),
                "refundRemark": $("#returnMoneyRemark").val(),
                "operatorId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                "operatorName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                "productList": listOrderRefundItems,
            }),
            success: function(result) {
                if(result.code == "0"){
                    layer.msg('修改成功', {icon: 6,time:1000});
                    setTimeout( function () {
                        var index =  parent.location.reload();
                        parent.layer.close(index)
                    },1000);
                }else{
                    isIng=false;
                    layer.msg(result.message, {icon: 5, time: 1000});
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                isIng = false;
            }
        });
        isIng = false;
        layer.close(curInds);

    }



}

/*跳至商品详情*/
function goToGoodsDetail(spuId) {
    sessionStorage.setItem("spuId_order", spuId);
    sessionStorage.setItem("spuId", spuId);
    console.log(8888)
    var index = layer.open({
        type: 2,
        title: "Code详情",
        content: "../../goods/goods-sku.html"
    });
    layer.full(index);
}

/*设置是否退运费*/
var isSetReturnFreight = 0; // 0-不退运费；1-退运费
function setReturnFreight(flag) {
    var freight = $('#freight').val(); // 退货取货运费
    var Return_goods = $("#Return_goods").text(); // 退货商品金额
    var Share_coupon = $("#Share_coupon").text(); // 分摊优惠
    var return_freight = 0; // 退运费（订单运费）

    if (flag == 1) {
        return_freight = $("#Share_freight").html();
        $("#return_freight").html(return_freight)
        isSetReturnFreight = 1;
        $(".tui").attr("onclick", "return false;");
        $(".tui").css({"color": "grey"});
        $(".notui").css({"color": "#1e79e9"});
        $(".notui").attr("onclick", "setReturnFreight(2)");
        yunfie=1
    } else {
        $("#return_freight").html(return_freight)
        isSetReturnFreight = 0;
        $(".notui").attr("onclick", "return false;");
        $(".notui").css({"color": "grey"});
        $(".tui").css({"color": "#1e79e9"});
        $(".tui").attr("onclick", "setReturnFreight(1)");
        yunfie=0
    }
    var refund_amount_final = Number(Return_goods) -Number(freight) - Number(Share_coupon) + Number(return_freight)-promotionvaluel-usedpoints;
    $('#refund_amount_final').html((refund_amount_final).toFixed(2))
}

//检索
function retrievaldatas(obj) {
    if($("#datatable").css("display")=="none"){
        setTimeout(function(){//因为是即时查询，需要用setTimeout进行延迟，让值写入到input内，再读取
            var storeId = document.getElementById('datatablejk');//获取table的id标识
            var rowsLength = storeId.rows.length;//表格总共有多少行
            var key = obj.value;//获取输入框的值
            var searchCol = 0;//要搜索的哪一列，这里是第一列，从0开始数起
            var numsall1=0
            for(var i=1;i<rowsLength;i++){//按表的行数进行循环，本例第一行是标题，所以i=1，从第二行开始筛选（从0数起）
                var searchTextall=''
                var searchText=$($(storeId.rows[i].cells[searchCol].children).children()[1]).find("div")
                for (var m=0;m<searchText.length;m++) {
                    searchTextall+=$($(searchText)[m]).html().trim()
                }
                if(searchTextall!=undefined){
                    if(searchTextall.match(key)){//用match函数进行筛选，如果input的值，即变量 key的值为空，返回的是ture，
                        numsall1++;
                        storeId.rows[i].style.display='';//显示行操作，
                    }else{
                        storeId.rows[i].style.display='none';//隐藏行操作
                    }
                }
            }
            if(numsall1==0){
                $.Huimodalalert('没有检索到数据',2000);
            }
        },200);//200为延时时间
    }else {
        setTimeout(function(){//因为是即时查询，需要用setTimeout进行延迟，让值写入到input内，再读取
            var storeId = document.getElementById('datatable');//获取table的id标识
            var rowsLength = storeId.rows.length;//表格总共有多少行
            var key = obj.value;//获取输入框的值
            var searchCol = 0;//要搜索的哪一列，这里是第一列，从0开始数起
            var numsall=0
            for(var i=1;i<rowsLength;i++){//按表的行数进行循环，本例第一行是标题，所以i=1，从第二行开始筛选（从0数起）
                var searchTextall=''
                var searchText=$($(storeId.rows[i].cells[searchCol].children).children()[1]).find("div")
                for (var m=0;m<searchText.length;m++) {
                    searchTextall+=$($(searchText)[m]).html().trim()
                }
                if(searchTextall!=undefined){
                    if(searchTextall.match(key)){//用match函数进行筛选，如果input的值，即变量 key的值为空，返回的是ture，
                        numsall++;
                        storeId.rows[i].style.display='';//显示行操作，
                    }else{
                        storeId.rows[i].style.display='none';//隐藏行操作
                    }}
            }
            if(numsall==0){
                $.Huimodalalert('没有检索到数据',2000);
            }
        },200);//200为延时时间
    }


}